import java.text.DecimalFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

// This class manages the downup table's data.
class DownUpTableModel extends AbstractTableModel implements Observer
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 9104779324187668842L;

	// These are the names for the table's columns.
	private static final String[] columnNames = { "Contents Provider ID",
			"Content ID", "Item Title", "Feed URL", "File Size(MB)",
			"Download Progress", "Upload Progress", "Status" };

	// These are the classes for each column's values.
	@SuppressWarnings("unchecked")
	private static final Class[] columnClasses = { String.class, String.class,
			String.class, String.class, String.class, JProgressBar.class,
			JProgressBar.class, String.class };

	// The table's list of downups.
	private ArrayList<DownUp> downupList = new ArrayList<DownUp>();

	// Add a new downup to the table.
	public void adddownup(DownUp downup)
	{

		// Register to be notified when the downup changes.
		downup.addObserver(this);

		downupList.add(downup);

		// Fire table row insertion notification to table.
		fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
	}

	// Get a downup for the specified row.
	public DownUp getDownup(int row)
	{
		return (DownUp) downupList.get(row);
	}

	// Remove a downup from the list.
	public void clearDownup(int row)
	{
		downupList.remove(row);

		// Fire table row deletion notification to table.
		fireTableRowsDeleted(row, row);
	}

	// Get table's column count.
	public int getColumnCount()
	{
		return columnNames.length;
	}

	// Get a column's name.
	public String getColumnName(int col)
	{
		return columnNames[col];
	}

	// Get a column's class.
	@SuppressWarnings("unchecked")
	public Class getColumnClass(int col)
	{
		return columnClasses[col];
	}

	// Get table's row count.
	public int getRowCount()
	{
		return downupList.size();
	}

	// Get value for a specific row and column combination.
	public Object getValueAt(int row, int col)
	{

		DownUp downup = (DownUp) downupList.get(row);

		switch (col)
		{
		case 0:
			return downup.getCPID();
		case 1:
			return downup.getCID();
		case 2:
			return downup.getTitle();
		case 3:
			return downup.getUrl();
		case 4:
			String pattern = "0.##";
			DecimalFormat df = new DecimalFormat(pattern);
			float size = downup.getSize();
			return (size == -1) ? "" : df.format(size);
		case 5:
			return new Float(downup.getProgress());
		case 6:
			return new Float(downup.getupProgress());
		case 7:
			return DownUp.STATUSES[downup.getStatus()];
		}
		return "";
	}

	/*
	 * Update is called when a downup notifies its observers of any changes
	 */
	public void update(Observable o, Object arg)
	{
		int index = downupList.indexOf(o);

		// Fire table row update notification to table.
		fireTableRowsUpdated(index, index);
	}
}